const sql = require('sqlite3').verbose(),
      path = require('path'),
      fs = require('fs');

const databasePath = path.resolve(__dirname, '..', 'data', 'database.db');

if(!fs.existsSync(databasePath)) {
    console.warn(
        '\n>>>>> WARNING <<<<<',
        '\nDatabase is not initialized!',
        '\n\n"npm run db:initialize" to initialize database',
        '\n\n... Process aborted ...\n'
    );

    process.exit(1);
}

const db = new sql.Database(databasePath);

const query = (queryString, parameters) => new Promise((resolve, reject) => {
    db.serialize(() => {
        db.all(queryString, parameters, (err, rows) => {
            if(err) return reject(err);
            resolve(rows);
        });
    });
});

const close = () => new Promise((resolve, reject) => {
    db.close(err => {
        if(err) return reject(err);
        resolve();
    });
});

module.exports = {
    query,
    close
};
